﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Web.Mvc;
using System.Web.Routing;
using ShopB2C.Entity;
using ShopB2C.Enums;
using ShopB2C.Helper;
using ShopB2C.Interfaces;
using ShopB2C.ViewModels;
using System.Linq;

namespace ShopB2C.Controllers.Manager
{
    public partial class ProductController : BaseController
    {
        private static IProductOperate _productOperate;
        private static IProductPreview _productPreView;
        private static IClassify _classify;
        private static IBrand _brand;

        private const string _moduleKey = "Product";
        private const int _classId = 1;

        private static string _imageRoot;

        public ProductController()
        {
            _productOperate = DataBaseExecuter.CreateClassByName<IProductOperate>("ProductOperate");
            _productPreView = DataBaseExecuter.CreateClassByName<IProductPreview>("ProductPreView");
            _classify = DataBaseExecuter.CreateClassByName<IClassify>("Classify");
            _brand = DataBaseExecuter.CreateClassByName<IBrand>("Brand");
            _imageRoot = "/ProductPictures";
        }

        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);

            this.SiteMapPathAdd("首页");
            this.SiteMapPathAdd("商品管理", Url.Action("ProductList"));
        }

        #region 基础信息
        /// <summary>
        /// 增加商品显示框
        /// </summary>
        public ActionResult New()
        {

            ViewData["SelectedValue"] = "0";

            List<BrandEntity> brandList = _brand.GetBrandList(string.Empty) ?? new List<BrandEntity>();
            brandList.Insert(0, new BrandEntity());

            ProductViewModel viewModel = new ProductViewModel()
            {
                ClassifyList = _classify.GetClassifyByModuleKey(_moduleKey),
                BrandList = brandList,
                ProductView = new ProductEntity() { SaleDateTime = DateTime.Now, IsActive = true, DisCount = 1 }

            };

            return View("BasicPost", viewModel);
        }
        /// <summary>
        /// 修改商品基础信息框
        /// </summary>
        public ActionResult Edit([DefaultValue(0)]int productId)
        {

            ProductEntity product = _productOperate.GetBasicById(productId);
            if (product == null)
                return RedirectToAction("New");

            List<BrandEntity> brandList = _brand.GetBrandList(string.Empty) ?? new List<BrandEntity>();
            brandList.Insert(0, new BrandEntity());

            ProductViewModel viewModel = new ProductViewModel()
            {
                ProductView = product,
                ClassifyList = _classify.GetClassifyByModuleKey(_moduleKey),
                MemberDiscount = _productPreView.MemberDiscount(productId),
                BrandList = brandList

            };

            ViewData["SelectedValue"] = product.ClassId;
            ViewData["ProductId"] = productId;
            return View("BasicPost", viewModel);
        }
        /// <summary>
        /// 保存商品基础信息
        /// </summary>
        [HttpPost]
        public ActionResult SaveBasic(
            ProductEntity product
            , [DefaultValue(false)]bool setpNext /* 如果参数setp为True则跳转到下一步，否则跳转到保存后的基础信息页面*/
            , DateTime? tbSaleD /*加入日期*/
            , [DefaultValue(0)] int tbSaleH /*加入时间*/
            , [DefaultValue(0)]int tbSaleM /*加入分*/
              )
        {

            MessageHelper msg = new MessageHelper("operateproduct");
            msg.AddBody(1);
            //产品名称不能为空
            msg.Required(product.ProductName, 1);
            // 产品主标题不能为空
            msg.Required(product.SubName, 2);
            //一个或者多个项目没有通过验证
            if (!msg.IsValid)
                return MessageResult(msg.CreateMessage());

            // 计算折扣
            if (product.Price <= 0)
            {
                product.Price = 0;
                product.DisCount = 1;
            }
            if (product.Price > 0)
                product.DisCount = product.DisCount / (double)product.Price;


            #region 构造销售时间
            // 构造加入时间
            tbSaleD = tbSaleD ?? DateTime.Now;
            tbSaleH = tbSaleH > 23 ? 23 : tbSaleH;
            tbSaleH = tbSaleH < 0 ? 0 : tbSaleH;
            tbSaleM = tbSaleM < 0 ? 0 : tbSaleM;
            tbSaleM = tbSaleM > 60 ? 60 : tbSaleM;
            product.SaleDateTime = Convert.ToDateTime(string.Format("{0} {1}:{2}:00", ((DateTime)tbSaleD).ToString("d"), tbSaleH, tbSaleM));

            #endregion

            int result = _productOperate.SaveProductBasic(product);

            #region 会员打折

            // 保存会员折扣
            if (result > 0 && Request.Form["LevelId"] != null)
            {
                List<UserLevelEntity> level = new List<UserLevelEntity>();

                string[] levelIds = Request.Form.GetValues("LevelId");
                string[] memberDiscounts = Request.Form.GetValues("MemberDiscount");
                string[] isDiscounts = Request.Form.GetValues("IsDiscount");

                int levleId;
                bool isDiscount;
                double memberDiscount;

                for (int i = 0; i < levelIds.Length; i++)
                {
                    int.TryParse(levelIds[i], out levleId);
                    bool.TryParse(isDiscounts[i], out isDiscount);
                    double.TryParse(memberDiscounts[i], out memberDiscount);

                    // 计算折扣
                    if (product.Price <= 0)
                    {
                        product.Price = 0;
                        memberDiscount = 1;
                    }

                    if (product.Price > 0)
                        memberDiscount = memberDiscount / (double)product.Price;


                    _productOperate.SaveMemberDiscount(new UserLevelEntity()
                    {
                        IsDiscount = isDiscount,
                        Discount = memberDiscount,
                        LevelId = levleId,
                        Sequence = result
                    });
                }

            }

            #endregion


            return setpNext
                ? RedirectToAction("Property", new { ProductId = result })
                : RedirectToAction("Edit", new { ProductId = result });
        }

        #endregion

        #region 批量操作

        [HttpPost]
        public ActionResult BatchAction()
        {
            string id = Request.Form["Ids"];
            string ac = Request.Form["ActionType"];
            string val = Request.Form["Value"];

            if (!string.IsNullOrEmpty(id))
            {


            }

            return new EmptyResult();
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        [HttpPost]
        public ActionResult DeleteProduct()
        {
            if (Request.Form["ProductId"] != null)
            {
                string[] ids = Request.Form.GetValues("ProductId");
                foreach (string item in ids)
                {
                    //try
                    //{
                    int result = _productOperate.DeleteProduct(Convert.ToInt32(item));
                    // 成功删除后删除图片,本来应该用事物的，暂时做个标记
                    if (result > 0)
                    {

                        System.IO.Directory.Delete(Server.MapPath(string.Format("{0}/{1}", _imageRoot, item)), true);

                    }
                    //}
                    //catch
                    //{
                    //}
                }
            }
            return new EmptyResult();
        }
        /// <summary>
        /// 批量激活
        /// </summary>
        [HttpPost]
        public ActionResult BatchActive([DefaultValue(false)]bool active)
        {
            if (Request.Form["ProductId"] != null)
            {
                try
                {
                    string[] ids = Request.Form.GetValues("ProductId");
                    foreach (string item in ids)
                    {
                        _productOperate.ChangeActive(Convert.ToInt32(item), active);
                    }
                }
                catch
                {

                }
            }

            return new EmptyResult();
        }
        /// <summary>
        /// 批量更新库存
        /// </summary>
        [HttpPost]
        public ActionResult BatchUpdateStock([DefaultValue(0)]int stockCount)
        {
            if (Request.Form["ProductId"] != null)
            {
                try
                {
                    string[] ids = Request.Form.GetValues("ProductId");
                    foreach (string item in ids)
                    {
                        _productOperate.UpdateStock(Convert.ToInt32(item), stockCount);
                    }
                }
                catch
                {

                }
            }
            return new EmptyResult();
        }
        /// <summary>
        /// 批量更新上架时间
        /// </summary>
        public ActionResult BatchSaleDateTime(DateTime? saleDateTime)
        {
            if (Request.Form["ProductId"] != null)
            {
                try
                {
                    string[] ids = Request.Form.GetValues("ProductId");
                    foreach (string item in ids)
                    {
                        _productOperate.UpdateSalesDateTime(Convert.ToInt32(item), saleDateTime ?? DateTime.Now);
                    }
                }
                catch
                {

                }
            }
            return new EmptyResult();
        }
        /// <summary>
        /// 批量打折
        /// </summary>
        public ActionResult BatchDiscount([DefaultValue(1D)]double discount)
        {
            if (Request.Form["ProductId"] != null)
            {
                try
                {
                    string[] ids = Request.Form.GetValues("ProductId");
                    foreach (string item in ids)
                    {
                        _productOperate.Discount(Convert.ToInt32(item), discount);
                    }
                }
                catch
                {

                }
            }
            return new EmptyResult();
        }

        #endregion

        #region 属性

        /// <summary>
        /// 商品的属性列表
        /// </summary>
        public ActionResult Property([DefaultValue(0)]int productId)
        {
            ViewData["ProductId"] = productId;
            ProductEntity product = _productOperate.GetBasicById(productId);
            if (product == null)
                return RedirectToAction("New");

            ViewData["ClassList"] = _classify.GetClassifyByModuleKey(_moduleKey);
            ViewData["ClassId"] = product.ClassId;
            return View();
        }
        /// <summary>
        /// 更改分类
        /// </summary>
        public ActionResult ChangeClass([DefaultValue(0)]int productId, int? classId)
        {
            List<ProductPropertyEntity> propertyList = _productPreView.PropertyList(productId, classId);
            return View("PropertyList", propertyList);
        }
        /// <summary>
        /// 保存属性
        /// </summary>
        [HttpPost]
        public ActionResult SaveProperty(
            [DefaultValue(0)]int productId
            , [DefaultValue(0)]int classId)
        {
            // 保存并回到上一页
            bool next = Request.QueryString["next"] != null ? true : false;
            // 保存并转到下一页
            bool front = Request.QueryString["front"] != null ? true : false;
            // 更改分类
            int result = _productOperate.ChangeClass(productId, classId);

            #region 修改属性
            if (Request.Form["ProductPropertyId"] != null)
            {
                string[] ids = Request.Form.GetValues("ProductPropertyId");
                string[] pds = Request.Form.GetValues("PropertyId");
                string[] vals = Request.Form.GetValues("PropertyValId");

                List<ProductPropertyEntity> propertyList = new List<ProductPropertyEntity>();
                for (int i = 0; i < ids.Length; i++)
                {
                    propertyList.Add(new ProductPropertyEntity()
                    {
                        ProductId = productId,
                        ProductPropertyId = Convert.ToInt32(ids[i]),
                        PropertyId = Convert.ToInt32(pds[i]),
                        PropertyValId = Convert.ToInt32(vals[i])
                    });
                }
                _productOperate.SaveProperty(propertyList);
            }
            #endregion

            // 如果参数 front 和 next 全部为空，保存后则返回到本页
            if (!next && !front)
                return RedirectToAction("Property", new { ProductId = productId });
            return front
                ? RedirectToAction("Edit", new { ProductId = productId })
                : RedirectToAction("ExtendProperty", new { ProductId = productId });

        }
        /// <summary>
        /// 获取该属性下的值
        /// </summary>
        public ActionResult PropertyVals([DefaultValue(0)]int propertyId
            , [DefaultValue(0)]int cid)
        {
            int pageCount = 0;
            List<ClassifyPropertyValEntity> valList = _classify.GetPropertyValByProperty(propertyId, int.MaxValue, 0, out pageCount);
            ViewData["ValList"] = valList;
            ViewData["Cid"] = cid;
            return View();
        }

        #endregion

        #region 扩展属性

        /// <summary>
        /// 更多高级属性
        /// </summary>
        public ActionResult ExtendProperty([DefaultValue(0)]int productId)
        {
            ViewData["ProductId"] = productId;
            List<ProductExtendEntity> extendList = _productPreView.ProductExtendList(productId);
            return View(extendList);
        }
        /// <summary>
        /// 更多高级属性
        /// </summary>
        /// <param name="productId">关联的产品ID</param>
        [HttpPost]
        public ActionResult ExtendProperty([DefaultValue(0)]int productId, bool? c)
        {
            bool next = Request.QueryString["next"] != null ? true : false;
            bool front = Request.QueryString["front"] != null ? true : false;

            if (Request.Form["extendKey"] != null)
            {

                string[] keys = Request.Form.GetValues("extendKey");
                string[] vals = Request.Form.GetValues("extendValue");
                string[] ids = Request.Form.GetValues("extendId");
                string[] sequences = Request.Form.GetValues("Sequence");

                for (int i = 0; i < keys.Length; i++)
                {
                    int sequence, extendId;
                    int.TryParse(ids[i], out extendId);
                    int.TryParse(sequences[i], out sequence);

                    _productOperate.SaveExtend(new ProductExtendEntity()
                    {
                        ExtendId = extendId,
                        ExtendKey = keys[i],
                        ExtendValue = vals[i],
                        Sequence = sequence,
                        ProductId = productId
                    });
                }

            }
            if (!next && !front)
                return RedirectToAction("ExtendProperty", new { ProductId = productId });

            return front
                ? RedirectToAction("Property", new { ProductId = productId })
                : RedirectToAction("Album", new { ProductId = productId });
        }
        /// <summary>
        /// 删除扩展高级属性
        /// </summary>
        public ActionResult DeleteExtendItem([DefaultValue(0)]int extendId)
        {
            _productOperate.DeleteExtendItem(extendId);

            return new EmptyResult();
        }

        #endregion

        #region 图片
        /// <summary>
        /// 图片扩展
        /// </summary>
        public ActionResult Album([DefaultValue(0)]int productId)
        {
            List<ProductImageEntity> imageList = _productPreView.GetImageList(productId);
            ViewData["ImageList"] = imageList;
            ViewData["ProductId"] = productId;
            ViewData["ImageRoot"] = _imageRoot;

            return View();
        }
        /// <summary>
        /// 保存图片扩展
        /// </summary>
        [HttpPost]
        public ActionResult SaveImageItem(
            [DefaultValue("")]string filePath
            , [DefaultValue(false)]bool isCover
            , [DefaultValue("")] string description
            , [DefaultValue(0)]int imageId
            , [DefaultValue("")]string imageName
            , [DefaultValue(0)] int sequence
            , [DefaultValue("")] string title
            , [DefaultValue(0)]int productId)
        {

            MessageException message = new MessageException() { Status = MessageStatus.Ok, Body = "操作成功!" };

            imageName = string.IsNullOrEmpty(imageName) ? Path.GetFileName(filePath) : imageName;
            imageName = Server.UrlDecode(imageName);
            string sourceFileName = Server.MapPath(Server.UrlDecode(filePath));
            string destDirectory = string.Format("/{0}/{1}", _imageRoot, productId);
            string destFileName = Server.MapPath(string.Format("{0}/{1}", destDirectory, imageName));
            string smailDestFileName = Server.MapPath(string.Format("{0}/s_{1}", destDirectory, imageName));

            if (System.IO.File.Exists(sourceFileName))
            {
                try
                {
                    //检查文件夹
                    if (!System.IO.Directory.Exists(Server.MapPath(destDirectory)))
                        System.IO.Directory.CreateDirectory(Server.MapPath(destDirectory));
                    // 移动图片
                    // System.IO.File.Copy(sourceFileName , destFileName , true);

                    //生成大图
                    using (FileStream thumbFS = System.IO.File.Open(destFileName, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        MemoryStream thumbMS = ThumbImageHelper.RateCuteThumbPhoto(1500, 1500, sourceFileName, true);
                        byte[] thumbBytes = thumbMS.ToArray();
                        thumbFS.Position = 0;
                        thumbFS.Write(thumbBytes, 0, thumbBytes.Length);
                        thumbFS.Flush();
                        thumbFS.Close();
                    }

                    //生成缩略图
                    using (FileStream thumbFS = System.IO.File.Open(smailDestFileName, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        MemoryStream thumbMS = ThumbImageHelper.ThumbPhoto(300, 300, destFileName, true);
                        byte[] thumbBytes = thumbMS.ToArray();
                        thumbFS.Position = 0;
                        thumbFS.Write(thumbBytes, 0, thumbBytes.Length);
                        thumbFS.Flush();
                        thumbFS.Close();
                    }

                    int result = _productOperate.SaveImage(new ProductImageEntity()
                    {
                        Description = description.Trim(),
                        ImageId = (int)imageId,
                        ImageName = imageName.Trim(),
                        IsCover = (bool)isCover,
                        ProductId = productId,
                        Sequence = (int)sequence,
                        Title = title.Trim()
                    });

                    if (result < 1) { message.Body = "数据库操作返回0!没有行受到影响!操作失败!可能的原因是已经存在相同的图片"; message.Status = MessageStatus.Error; }
                }
                catch (Exception e)
                {
                    message.Status = MessageStatus.Error;
                    message.Body = e.Message;

                }

            }
            else
            {
                message.Status = MessageStatus.Waring;
                message.Body = "原文件不存在!插入失败!没有行受到影响!";
            }

            return Json(message);
        }
        /// <summary>
        /// 显示插入窗口
        /// </summary>
        public ActionResult AlbumItemPost()
        {
            if (Request.Form["ImageId"] != null)
            {
                string[] ids = Request.Form.GetValues("ImageId");
                string[] ss = Request.Form.GetValues("Sequence");
                string[] ts = Request.Form.GetValues("tbTitle");
                string[] des = Request.Form.GetValues("Description");

                int imageId, sequence;

                for (int i = 0; i < ids.Length; i++)
                {
                    int.TryParse(ids[i], out imageId);
                    int.TryParse(ss[i], out sequence);

                    _productOperate.UpdateImageDescription(imageId, ts[i], des[i], sequence);
                }

            }

            return new EmptyResult();
        }
        /// <summary>
        /// 从图片扩展中删除图片
        /// </summary>
        [HttpPost]
        public ActionResult DeleteImageItem()
        {
            MessageException message = new MessageException() { Status = MessageStatus.Ok, Body = "" };
            if (Request.Form["ImageId"] != null)
            {
                string[] ids = Request.Form.GetValues("ImageId");
                List<ProductImageEntity> imageList = _productOperate.DeleteImage(ids);
                //删除图片
                foreach (var item in imageList)
                {
                    try
                    {
                        string fileDirectory = Server.MapPath(string.Format("{0}/{1}", _imageRoot, item.ProductId));
                        System.IO.File.Delete(string.Format("{0}/{1}", fileDirectory, item.ImageName));
                        System.IO.File.Delete(string.Format("{0}/s_{1}", fileDirectory, item.ImageName));
                    }
                    catch (Exception e)
                    {
                        message.Status = MessageStatus.Error;
                        message.Body += string.Format("{0}\n", e.Message);
                    }
                }
            }
            return Json(message);
        }
        /// <summary>
        /// 设置封面
        /// </summary>
        [HttpPost]
        public ActionResult SetCover([DefaultValue(0)]int imageId)
        {
            MessageException message = new MessageException() { Status = MessageStatus.Ok, Body = "操作成功!" };
            int result = _productOperate.SetCover(imageId);
            if (result < 1) { message.Status = MessageStatus.Error; message.Body = "没有行受到影响!操作失败!"; }
            return Json(message);
        }

        #endregion

        #region 详细信息

        /// <summary>
        /// 商品详细信息
        /// </summary>
        public ActionResult Details([DefaultValue(0)]int productId)
        {
            ProductDetailsEntity details = _productPreView.GetDetails(productId);
            ViewData["Details"] = details != null ? details.Detail : string.Empty;
            ViewData["SaveAction"] = "SaveDetails";
            ViewData["ProductId"] = productId;
            ViewData["CurrentSetp"] = "第四步:详细介绍";
            ViewData["NextSetp"] = "<input type=\"button\" name=\"btnNext\" value=\"下一步:包装清单\" />";
            ViewData["FrontSetp"] = "上一步:商品图片";
            return View("DetailsPost");
        }
        /// <summary>
        /// 保存商品详细信息
        /// </summary>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveDetails([DefaultValue(0)]int productId, [DefaultValue("")]string details)
        {

            bool next = Request.QueryString["next"] != null ? true : false;
            bool front = Request.QueryString["front"] != null ? true : false;
            bool finish = Request.QueryString["Finish"] != null ? true : false;

            _productOperate.SaveDetails(new ProductDetailsEntity()
            {
                ProductId = productId,
                Detail = details,
                Services = "Detail"
            });
            if (!next && !front && !finish)
                return RedirectToAction("Details", new { ProductId = productId });
            if (finish)
                return RedirectToAction("PreView", new { ProductId = productId });
            return front
                ? RedirectToAction("Album", new { ProductId = productId })
                : RedirectToAction("PackList", new { ProductId = productId });
        }

        #endregion

        #region 包装清单
        /// <summary>
        /// 包装清单
        /// </summary>
        public ActionResult PackList([DefaultValue(0)]int productId)
        {
            ViewData["SaveAction"] = "SavePackList";
            ProductDetailsEntity details = _productPreView.GetDetails(productId);
            ViewData["Details"] = details != null ? details.PackList : string.Empty;
            ViewData["ProductId"] = productId;
            ViewData["CurrentSetp"] = "马上就完成了(五):包装清单";
            ViewData["NextSetp"] = "<input type=\"button\" name=\"btnNext\" value=\"下一步:售后服务\" />";
            ViewData["FrontSetp"] = "上一步:详细介绍";
            return View("DetailsPost");
        }
        /// <summary>
        /// 保存包装清单
        /// </summary>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SavePackList([DefaultValue(0)]int productId, [DefaultValue("")]string details)
        {
            bool next = Request.QueryString["next"] != null ? true : false;
            bool front = Request.QueryString["front"] != null ? true : false;
            bool finish = Request.QueryString["Finish"] != null ? true : false;

            _productOperate.SaveDetails(new ProductDetailsEntity()
            {
                ProductId = productId,
                Detail = details,
                Services = "PackList"
            });

            if (!next && !front && !finish)
                return RedirectToAction("PackList", new { ProductId = productId });
            if (finish)
                return RedirectToAction("PreView", new { ProductId = productId });
            return front
                ? RedirectToAction("Details", new { ProductId = productId })
                : RedirectToAction("Services", new { ProductId = productId });
        }

        #endregion

        #region 售后服务

        /// <summary>
        /// 售后服务
        /// </summary>
        /// <param name="productId"></param>
        public ActionResult Services([DefaultValue(0)]int productId)
        {
            ViewData["SaveAction"] = "SaveServcies";
            ProductDetailsEntity details = _productPreView.GetDetails(productId);
            ViewData["Details"] = details != null ? details.Services : string.Empty;
            ViewData["ProductId"] = productId;
            ViewData["CurrentSetp"] = "最后一步(六):售后服务";
            ViewData["FrontSetp"] = "上一步包装清单";
            ViewData["NextSetp"] = "<input type=\"button\" name=\"btnNext\" value=\"下一步:相关产品\" />";
            return View("DetailsPost");
        }
        /// <summary>
        /// 服务方式
        /// </summary>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveServcies([DefaultValue(0)]int productId, [DefaultValue("")]string details)
        {
            bool front = Request.QueryString["front"] != null ? true : false;
            bool finish = Request.QueryString["Finish"] != null ? true : false;
            bool next = Request.QueryString["next"] != null ? true : false;

            _productOperate.SaveDetails(new ProductDetailsEntity()
            {
                ProductId = productId,
                Detail = details,
                Services = "Services"
            });

            if (!front && !next && !finish)
                return RedirectToAction("Services", new { ProductId = productId });
            if (finish)
                return RedirectToAction("PreView", new { ProductId = productId });
            return front
                ? RedirectToAction("PackList", new { ProductId = productId })
                : RedirectToAction("Relate", new { ProductId = productId });
        }

        #endregion

        #region 相关产品
        /// <summary>
        /// 相同/类似产品
        /// </summary>
        /// <param name="productId">关联的产品ID</param>
        public ActionResult Relate([DefaultValue(0)]int productId)
        {
            ViewData["ProductId"] = productId;
            return View();
        }
        /// <summary>
        /// 
        /// </summary>
        [HttpGet]
        public ActionResult RelatePost(
            [DefaultValue(0)]int ProductId)
        {
            ProductPartEntity part = _productPreView.RelateList(ProductId);
            ViewData["ProductId"] = ProductId;
            this.ModelState.Remove("ProductId");
            return View(part);
        }
        /// <summary>
        /// 相同类似保存
        /// </summary>
        /// <param name="PrimaryKey">关联的产品主ID</param>
        /// <param name="title">标题：友好名称</param>
        [HttpPost]
        public ActionResult RelatePost(
            [DefaultValue(0)]int PrimaryKey,
            [DefaultValue("")]string title)
        {
            string relateIds = string.Empty;
            if (Request.Form["ProductId"] != null)
            {
                string[] ids = Request.Form.GetValues("ProductId");
                int productId = 0;
                foreach (string i in ids)
                {
                    int.TryParse(i, out productId);
                    relateIds += string.Format("{0},", productId);
                }
                relateIds = relateIds.Trim(',');
            }


            _productOperate.SaveRelate(relateIds, PrimaryKey, title);


            return new EmptyResult();
        }
        /// <summary>
        /// 相同产品
        /// </summary>
        public ActionResult Same([DefaultValue(0)]int productId, ProductPart moduleKey)
        {
            ViewData["PartTypeList"] = Methods.GetEnumsToList(typeof(PartType));
            ViewData["ClassList"] = _classify.GetClassifyByModuleKey(_moduleKey);
            ProductPartEntity part = _productPreView.SameProduct(productId, moduleKey)
                ?? new ProductPartEntity() { ProductList = new List<ProductEntity>(), IsVaild = true, Count = 4 };
            part.ModuleKey = string.Format("{0}-{1}", moduleKey, productId);
            this.ModelState.Remove("moduleKey");
            return View("PartPost", part);
        }


        #endregion


    }
}